package com.tudouji.framework.task;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.annotation.PostConstruct;

import com.flow.service.config.FlowConfig;
import com.flow.service.pojo.BasePojo;
import com.flow.service.pojo.flow.FlowTaskDetail;
import com.flow.service.pojo.flow.FlowTemp;
import com.flow.service.pojo.result.AdviceResult;
import com.flow.service.pojo.user.FlowUser;
import com.flow.service.process.service.IFlowTaskDetailService;
import com.flow.service.utils.ParserUtil;
import com.tudouji.project.system.domain.SysUser;
import com.tudouji.project.system.service.ISysUserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.weixin4j.WeixinException;
import org.weixin4j.component.MessageComponent;
import org.weixin4j.model.message.template.TemplateData;
import org.weixin4j.model.message.template.TemplateMessage;
import org.weixin4j.spring.WeixinTemplate;

import com.tudouji.common.utils.PotatojPostUtils;
import com.tudouji.project.noticeinfo.domain.Noticeinfo;
import com.tudouji.project.noticeinfo.service.INoticeinfoService;
import com.tudouji.project.system.domain.Tuser;
import com.tudouji.project.system.service.ISysConfigService;
import com.tudouji.project.system.service.ITuserService;

import lombok.extern.slf4j.Slf4j;

/**
 * 催办通知发送
 *
 * @author xiaxl
 *
 */

@Slf4j
@Component("remindSynTask")
public class RemindSynTask {



	@Autowired
	private ISysUserService userService;

	@Autowired
	private ISysConfigService configService;

	@Autowired
	private WeixinTemplate tem;

	private static WeixinTemplate weixinTemplate;

	@Autowired
	private IFlowTaskDetailService taskDetailService;

	@PostConstruct
	public void init() {
		weixinTemplate = tem;
	}

	public void remindTask(String start) {
		log.info("_______________remindTask start______________");
		SimpleDateFormat formate = new SimpleDateFormat("yyyy-MM-dd");
		Date now = null;
		if (StringUtils.isNotBlank(start)) {
			try {
				now = formate.parse(start);
			} catch (ParseException e) {
				e.printStackTrace();
			}
		} else {
			now = new Date();
		}
		FlowTaskDetail notice = new FlowTaskDetail();
		notice.setCreateTime(now);
		List<FlowTaskDetail> notices = taskDetailService.selectNotHandleList(notice);
		Map<String, String> map = new HashMap<>();
		for (FlowTaskDetail info : notices) {
			try {
				String[] rule = info.getRemindRule().split(",");
				int cnt = Integer.valueOf(rule[1]);
				// 获取最后一次催办时间与当前时间的间隔分钟数
				int minit = getSubMint(info.getLastRemindTime());
				log.info("____________minit____________"+minit);
				int create = getSubMint(info.getCreateTime());
				// 未超过催办次数且上一次催办时间已超过配置时间且已超过待办时效
				if ((info.getReminderTimes() < cnt && minit >= Integer.valueOf(rule[0])&& info.getTimeLimit() <= create)||(info.getReminderTimes()==0&&minit>=info.getTimeLimit())) {
					map.put("username", info.getReciever());
					map.put("handler", "");
					map.put("limitTime", info.getTimeLimit() + "");
					map.put("cnt", (info.getReminderTimes() + 1) + "");
					String remindmsg = assembleSms(info.getReminderMsg(), map);
					SysUser reciever = userService.selectUserById(info.getRecieverId());

					log.info("___________send remind msg___________");
					sendWechatMsg(info, remindmsg, reciever);
					// 督办人通知
					List<SysUser> users = userService.selectUserByLoginName(info.getSupervisor().split(","));
					for (SysUser user : users) {
						if (StringUtils.isNotBlank(user.getOpenid())) {
							map.put("username", user.getNickName());
							map.put("handler", info.getReciever());
							remindmsg = assembleSms(info.getReminderMsg(), map);
							sendWechatMsg(info, remindmsg, user);
						}
					}
					//更新通知
					log.info("___________update notice___________");
					info.setLastRemindTime(new Date());
					info.setUpdateTime(new Date());
					info.setReminderTimes(info.getReminderTimes()+1);
					taskDetailService.updateFlowTaskDetail(info);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		log.info("_______________remindTask end______________");
	}

	public int getSubMint(Date start) {
		Long st = start.getTime();
		Long ed = System.currentTimeMillis();
		Long min = (ed - st) / (1000 * 60);
		return min.intValue();
	}

	public String assembleSms(String mould, Map<String, String> paramMap) {
		for (Map.Entry<String, String> entry : paramMap.entrySet()) {
			mould = mould.replace("${" + entry.getKey() + "}", entry.getValue());
		}
		return mould;
	}

	public AdviceResult sendWechatMsg(FlowTaskDetail info, String msg, SysUser user) {
		AdviceResult result=new AdviceResult();
		if (org.apache.commons.lang3.StringUtils.isNotBlank(user.getOpenid())) {
			TemplateMessage templateMessage = new TemplateMessage();
			templateMessage.setTemplateId(FlowConfig.getTemplates().getWechat_reminder_templ());
			templateMessage.setOpenid(user.getOpenid());
			String backurl=info.getUrl();
			if (org.apache.commons.lang3.StringUtils.isNotBlank(backurl)) {
				if (info.getUrl().contains("?")) {
					if (StringUtils.isNotBlank(user.getOpenid()) && user.getOpenid().length() > 20) {
						backurl = info.getUrl() + "&openid=" + user.getOpenid() + "&status=" + info.getOrderStatus()
								+ "&code=" + info.getOrderCode();
					} else {
						backurl = info.getUrl() + "&status=" + info.getOrderStatus() + "&code=" + info.getOrderCode();
					}

				} else {
					if (StringUtils.isNotBlank(user.getOpenid()) && user.getOpenid().length() > 20) {
						backurl = info.getUrl() + "?openid=" + user.getOpenid() + "&status=" + info.getOrderStatus()
								+ "&code=" + info.getOrderCode();
					} else {
						backurl = info.getUrl() + "&status=" + info.getOrderStatus() + "&code=" + info.getOrderCode();
					}
				}
				System.out.println("-----------backurl2--------"+backurl);
				backurl = backurl.replace('#', '*');
				templateMessage.setUrl(backurl.trim());

				backurl = backurl.replace('*', '#');
				String[] srts = backurl.split("redirect_url=");
				String url = srts[1];
				result.setUrl(url);
			}

			List<TemplateData> templateDataList = new ArrayList<TemplateData>();

			TemplateData first = new TemplateData();
			first.setKey("first");

			first.setValue("您有1条新的流程催办提醒!");

			TemplateData keyword1 = new TemplateData();
			keyword1.setKey("keyword1");
			keyword1.setValue(info.getNoticeTitle());

			// 通知内容
			TemplateData keyword2 = new TemplateData();
			keyword2.setKey("keyword2");
			keyword2.setValue(msg);

			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			TemplateData keyword3 = new TemplateData();
			keyword3.setKey("keyword3");
			// 通知时间
			keyword3.setValue(format.format(new Date()));

			templateDataList.add(first);
			templateDataList.add(keyword1);
			templateDataList.add(keyword2);
			templateDataList.add(keyword3);
			templateMessage.setData(templateDataList);

			MessageComponent messageComponent = weixinTemplate.message();
			try {
				messageComponent.sendTemplateMessage(templateMessage);
				result.setResult("success");
			} catch (WeixinException e) {
				result.setResult(e.getMessage());
			}
		} else {
			result.setResult("no openid");
		}
		return result;
	}
}
